package com.hkts.beltweigher.config.httpclient;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassNameHttpAPIService
 * @Description
 * @Author yck
 * @Date2021-06-11 10:45
 * @Version V1.0
 **/

@Service
@Slf4j
public class
HttpAPIService {

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;

    @Autowired
    private PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;
    @Autowired
    private Message message;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url) throws Exception {
        StringBuffer sb = new StringBuffer();
        org.apache.http.client.HttpClient client = null;

        InputStream in = null;
        InputStreamReader isr = null;
        HttpGet get = new HttpGet();
        try {
            client = HttpConnectionManager.getHttpClient();
            get.setURI(new URI(url));
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() != 200) {
                get.abort();
                return null;
            }
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                in = entity.getContent();
            }
            if (response.getStatusLine().getStatusCode() == 200) {
                // 返回响应体的内容
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            return sb.toString();

        } catch (Exception e) {
            get.abort();
            e.printStackTrace();
            return null;
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url, Map<String, Object> map) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);

        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 调用不带参数的get请求
        return this.doGet(uriBuilder.build().toString());

    }


    /**
     * 不带参数post请求
     *
     * @param url
     * @return
     * @throws Exception
     */
   /* public HttpResult doPost(String url) throws Exception {

        return null;
    }*/
    public String postMap(String msg) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = "http://183.196.8.232:8006/send/sendMessage?type=" + message.getType() + "&msg=" + msg;
        HttpPost post = new HttpPost(url);
        log.error(msg);
        //将content生成entity
        CompletableFuture<Void> voidCompletableFuture1 = CompletableFuture.runAsync(() -> {
            CloseableHttpResponse response = null;
            try {
                response = httpClient.execute(post);            //发送请求并接收返回数据
                log.info("消息服务器:{}", response);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    httpClient.close();
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }, threadPoolExecutor);

        return null;
    }

    //判断是否需要发消息
    public void sendMessage(Integer type, String address, String msg) {

        msg=message.getCompany()+":"+msg;
        MsgCache msgCache = HttpCache.msgCache.get(address);
        Date date = new Date();
        Calendar c = new GregorianCalendar();
        c.setTime(date);
        c.add(Calendar.MINUTE, 30);
        if (msgCache == null && type.equals(MsgCache.OPEN)) {
            msgCache = new MsgCache(type, c.getTime().getTime());
            HttpCache.msgCache.put(address, msgCache);
           // this.postMap(msg);
        } else if (msgCache == null && type.equals(MsgCache.OFF)) {
            msgCache = new MsgCache(type, c.getTime().getTime());
            HttpCache.msgCache.put(address, msgCache);
            this.postMap(msg);
        } else if (msgCache != null && type.equals(MsgCache.OFF)) {
            if (!msgCache.getType().equals(type)) {
                msgCache = new MsgCache(type, c.getTime().getTime());
                HttpCache.msgCache.put(address, msgCache);
                this.postMap(msg);
            }else if(date.getTime()>msgCache.getTimeStamp()){
                msgCache = new MsgCache(type, c.getTime().getTime());
                HttpCache.msgCache.put(address, msgCache);
                this.postMap(msg);
            }
        } else if (msgCache != null && type.equals(MsgCache.OPEN)) {
            if (!msgCache.getType().equals(type)) {
                msgCache = new MsgCache(type, c.getTime().getTime());
                HttpCache.msgCache.put(address, msgCache);
                this.postMap(msg);
            }
        }
    }
}
